#/bin/bash
ImageName="${DS_SERIAL_NUMBER}--CreatedBy-${DS_USER_LOGIN}--`date \"+%Y-%m-%d_%H-%M-%S\"`"
BackupVolumeName="Denison Backup"
FullPathToImage="${DS_REPOSITORY_PATH}/Masters/.workInProgress/backupsInProgress/.${ImageName}"



function purgeOldBackups
{
	dir="${1}"
	min_size="+3G"

	echo "       Starting DMG Scan"
	echo "------------------------------"
	echo "Scanning '${dir}' for .dmg files ${min_size} in size"
	find "${dir}" -regex ".*\.dmg$" -size "${min_size}" -print0 | while read -d $'\0' f
	do
		if [ -f "${f}" ]
		then
			f_size=$(du -sh "${f}" | sed 's/\/.*$//' | sed 's/[^a-zA-Z0-9]*//g')
			f_name=$(basename "${f}")
			f_path=$(dirname "${f}")
			echo ""
			echo "..filename: ${f_name}"
			echo "......size: ${f_size}" 
			echo "......path: ${f_path}"
			rm -rf "${f}"
		else
			echo "Not a real path '${f}'"
		fi
	done
	echo "        Scan DMG complete"
	echo "------------------------------"
}


#
# create and mount the dmg
#
echo " - Creating 250g sparse dmg with HFS+ filesystem"
hdiutil create -size 250g -type SPARSE -fs HFS+ -volname "${BackupVolumeName}" -attach -plist -ov "${FullPathToImage}" > /tmp/specs.plist


echo " - Checking for valid mount point"
MountPoint=""
for i in 0 1 2
do
	MountPoint=`/usr/libexec/PlistBuddy /tmp/specs.plist -c\
		"Print system-entities:${i}:mount-point" 2>/dev/null`
	if [ -d "${MountPoint}" ]; then
		break
	fi
done
FullPathToImage=`/usr/libexec/PlistBuddy /tmp/specs.plist -c\
	"Print image-components:0"`
rm /tmp/specs.plist


if [ -d "${MountPoint}" ]; then
	echo " - Found ${MountPoint}"
else
	echo " - Unable to locate path '${MountPoint}', bailing out"
	exit 1
fi


#
# Iterate through all of the volumes in the /Volumes directory, making sure to
# skip over the symbolic link to '/'
startTime="`date \"+%s\"`"
for dir in /Volumes/*/*; do

	volumePath="`dirname \"${dir}\"`"
	volume="`basename \"${volumePath}\"`"
	folder="`basename \"${dir}\"`"

	# Make sure we aren't trying to backup the volume that we're backing up to
	if [ "${volume}" == "${BackupVolumeName}" ]; then
		continue
	fi

	# If the volume is a symbolic link, then skip it since it probably
	# points back to the root of the netbooted volume
	if [ -h "${volumePath}" -o -h "${dir}" ]; then
		continue
	fi

	
	# Make sure that the volume is a local one, we don't want start backing
	# up a network volume
	protocol="`diskutil info \"${volumePath}\" | grep \"Protocol\" | sed \"s/^[ ]*Protocol:[ ]*//\"`"

	if [ "${protocol}" != "" ]; then
		
		# Iterate through each folder within the volume so we can
		# selectively ignore common OS X directories

		# Skip common directories
		if [ "${folder}" == "dev"\
			-o "${folder}" == "Developer"\
			-o "${folder}" == "Applications"\
			-o "${folder}" == "Library"\
			-o "${folder}" == "System"\
			-o "${folder}" == "cores"\
			-o "${folder}" == "home"\
			-o "${folder}" == "Desc"\
			-o "${folder}" == "Info"\
			-o "${folder}" == "private"\
			-o "${folder}" == "tmp"\
			-o "${folder}" == "sbin"\
			-o "${folder}" == "bin"\
			-o "${folder}" == "var"\
			-o "${folder}" == "mach"\
			-o "${folder}" == "mach.sym"\
			-o "${folder}" == "mach_kernel"\
			-o "${folder}" == "mach_kernel.ctfsys"\
			-o "${folder}" == "etc"\
			-o "${folder}" == "Volumes"\
			-o "${folder}" == "Network"\
			-o "${folder}" == "Desktop DB"\
			-o "${folder}" == "Desktop DF"\
			-o "${folder}" == "net"\
			-o "${folder}" == "usr"\
			-o "${folder}" == "opt"\
			-o "${folder}" == "Quarantine"\
			-o "${folder}" == "Users"\
			]; then
			if [ "${folder}" == "Users" ]; then
				for users in "${dir}"/*; do
					user="`basename \"${users}\"`"
					if [ "${user}" != "macadmin" ]; then
						trash="${users}/.Trash"
						echo "EXAMINING USER: ${users}"

						if [ -d "${trash}" ]; then
							echo "  - Emptying trash..."
							`rm -Rf "${trash}"`
							echo "  - Emptying user cache..."
							`rm -Rf	"${users}/Library/Caches/"`
							echo "  - Emptying user logs..."
							`rm -Rf	"${users}/Library/Logs/"`
							echo "  - Emptying user PubSub..."
							`rm -Rf	"${users}/Library/PubSub/"`
							echo "  - Emptying user MobileSync Data..."
							`rm -Rf	"${users}/Library/Application Support/MobileSync"`
							echo "  - Removing iChat Icons"
							`rm -Rf "${users}/Pictures/iChat Icons"`
						fi
						purgeOldBackups "${users}"
						destDir="${MountPoint}/${volume}/${folder}/"
						`mkdir -p "${destDir}"`
						`cp -Rpf "${users}" "${destDir}"`
					fi
				done
			else
				echo " --SKIPPING \"${dir}\""
			fi
		else
			`mkdir -p "${MountPoint}/${volume}/${folder}"`
			`cp -Rpf "${dir}" "${MountPoint}/${volume}/${folder}"`
		fi
	fi
done


echo " - Unmounting ${MountPoint}"
hdiutil eject "${MountPoint}"
endTime="`date \"+%s\"`"

let totalTime=$endTime-$startTime

echo 
echo
echo "================================================================"
echo
echo ${ImageName}
echo "Created in ${totalTime} seconds"
echo
echo "================================================================"

theDir=`dirname "${FullPathToImage}"`
mv "${FullPathToImage}" "${theDir}/${ImageName}.dmg"
